package com.pz.gulimall.auth.service;

import com.alibaba.fastjson2.JSON;
import com.pz.gulimall.auth.feign.ProductFeign;
import com.pz.gulimall.auth.vo.res.ShopCarItemResVo;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import org.apache.commons.lang.ArrayUtils;
import org.apache.ibatis.reflection.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.pz.gulimall.auth.constan.CacheConstant.CART_CACHE_NAME;


@Service
public class CacheService {
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 从缓存中获取 key 的 值（cart值）
     * @param key
     * @return
     */
    public List<ShopCarItemResVo> getFromCache(String key) {
        // 获取指定的缓存
        Object o;
        try {
            o = cacheManager.getCache(CART_CACHE_NAME).get(key).get();
        }catch (NullPointerException e){
            // 缓存中不存在
            return new ArrayList<>();
        }
        return JSON.parseArray(JSON.toJSONBytes(o), ShopCarItemResVo.class);
    }

    /**
     * 获取当前登录用户的购物车的所有购物项
     */
    @Cacheable(value = CART_CACHE_NAME, key = "#loginId", sync = true)
    public List<ShopCarItemResVo> getCartItems(String loginId) {
        try {
            R ans = productFeign.getByLoginId(loginId);
            if(ans.getCode() == 0){
                List<ShopCarItemResVo> resVos = ans.getDataArray(ShopCarItemResVo.class);
                //处理 saleAttrs 将其由数据库结构转换为缓存结构
                return resVos.stream().peek(item -> {
                            String[] str = item.getSaleAttrs().get(0).split(";");
                            item.setSaleAttrs(List.of(str));
                            item.setTotalPrice();
                        }).collect(Collectors.toList());
            } else {
                throw new RRException(ans.getMsg(), ans.getCode());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_PRODUCT_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_PRODUCT_FAILED.getCode());
        }
    }

    @CacheEvict(value = CART_CACHE_NAME, key = "#loginId")
    public void DelCache(String loginId){
        System.out.println("======>>>>>>移除完成<<<<<<<========="+loginId);
    }

}
